package com.ruge.core.tool;

import com.ruge.tool.http.HttpTool;
import com.ruge.tool.json.JsonTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * description: BaiduTool
 * create time at 2022/6/6 11:31
 *
 * @author alice.ruge
 * @since 0.0.3
 */

@Slf4j
@Component
public class BaiduTool {


    public static final String BAIDU_MAP = "http://api.map.baidu.com/place/v2/search";
    /**
     * 百度的ak
     * baic  private static final String AK = "r4KODxZAANe1LO05OcshYj1ZskxyTi70";
     */
    private static final String AK = "tY5G3L9XWbdxRqg6QmyPxNTFaiw4R47Q";
    public static final Long DEFAULT_RADIUS = 2000L;
    public static final Long RADIUS = 20000L;

    /**
     * 调用百度地图查询省市区
     *
     * @param lat 纬度
     * @param lon 经度
     * @return 省市区
     */
    public static String addressByLocation(Double lat, Double lon, Long radius) {
        String address = "";
        if (radius < RADIUS) {
            String location = (lat + "," + lon).trim();
            String query = "大学";
            String output = "json";
            String uri = BAIDU_MAP + "?query=" + query + "&location=" + location + "&radius=" + radius + "&output=" + output + "&ak=" + AK;
            String result = HttpTool.get(uri);
            Map<String, Object> jsonToMap = JsonTool.getJsonToMap(result);
            Object status = jsonToMap.get("status");
            List<Map<String, Object>> results = JsonTool.getObjToMaps(jsonToMap.get("results"));
            // 成功的状态 status = 0
            String keyword = "0";
            if (!keyword.equals(status)) {
                address = "调用百度地图返回错误，地址获取失败！！！" + uri.concat("response:").concat(jsonToMap.toString());
                log.error(address);
            } else if (keyword.equals(status) && results.isEmpty()) {
                radius = radius + 20;
                return addressByLocation(lat, lon, radius);
            } else {
                //字符串解析
                String province = String.valueOf((results.get(0)).get("province"));
                String city = String.valueOf((results.get(0)).get("city"));
                String area = String.valueOf((results.get(0)).get("area"));
                String name = String.valueOf((results.get(0)).get("name"));
                address = province + "," + city + "," + area + "," + name;
            }
        }
        return address;
    }
}